package server

import (
	"fmt"
	"net/http"
	"time"

	"github.com/kataras/fasthttp"
	"go.uber.org/zap"
)

// NovelsSer  novels server conf
type NovelsSer struct {
	Key        string `json:"key"`
	SearchKey  string `json:"search_key"`
	Addr       string `json:"addr"`
	httpClient *fasthttp.Client
}

func newNovelsSer() *NovelsSer {
	return &NovelsSer{
		httpClient: &fasthttp.Client{},
	}
}

// search 搜索
func (ns *NovelsSer) search(novel string) ([]byte, error) {
	url := fmt.Sprintf("%s%s=%s", ns.Addr, ns.SearchKey, novel)
	statusCode, body, err := ns.httpClient.GetTimeout(nil, url, time.Second)
	// buf = body
	if err != nil {
		Logger.Warn("http", zap.Error(err))
		return nil, err
	}
	if statusCode != http.StatusOK {
		Logger.Warn("http", zap.Error(err))
		return nil, err
	}

	return body, nil
}

func requestHandler(ctx *fasthttp.RequestCtx) {
	fmt.Fprintf(ctx, "Hello, world!\n\n")

	fmt.Fprintf(ctx, "Request method is %q\n", ctx.Method())
	fmt.Fprintf(ctx, "RequestURI is %q\n", ctx.RequestURI())
	fmt.Fprintf(ctx, "Requested path is %q\n", ctx.Path())
	fmt.Fprintf(ctx, "Host is %q\n", ctx.Host())
	fmt.Fprintf(ctx, "Query string is %q\n", ctx.QueryArgs())
	fmt.Fprintf(ctx, "User-Agent is %q\n", ctx.UserAgent())
	fmt.Fprintf(ctx, "Connection has been established at %s\n", ctx.ConnTime())
	fmt.Fprintf(ctx, "Request has been started at %s\n", ctx.Time())
	fmt.Fprintf(ctx, "Serial request number for the current connection is %d\n", ctx.ConnRequestNum())
	fmt.Fprintf(ctx, "Your ip is %q\n\n", ctx.RemoteIP())

	fmt.Fprintf(ctx, "Raw request is:\n---CUT---\n%s\n---CUT---", &ctx.Request)

	ctx.SetContentType("text/plain; charset=utf8")

	// Set arbitrary headers
	ctx.Response.Header.Set("X-My-Header", "my-header-value")

	// Set cookies
	var c fasthttp.Cookie
	c.SetKey("cookie-name")
	c.SetValue("cookie-value")
	ctx.Response.Header.SetCookie(&c)
}
